package com.isman.placeslist;

import java.lang.reflect.Type;
import java.util.ArrayList;

import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import net.londatiga.android.QuickAction.OnActionItemClickListener;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isman.placeslist.apiobject.Session;
import com.isman.placeslist.apiobject.Status;
import com.isman.placeslist.setting.ProjectPref;
import com.isman.placeslist.ws.AsyncRunnerHeadler;
import com.isman.placeslist.ws.ServiceProvider;

public class PageFeed extends Activity {
	private static final int STATUS_DETAIL = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_feed);
		mSession = new Session();
		mStatusList = new ArrayList<Status>();
		mStatusAdapter = new StatusAdapter(this);
		ProjectPref.restoreSession(mSession, this);

		vLvList = (ListView) findViewById(R.id.lvw_feed_list);
		vLvList.setAdapter(mStatusAdapter);
		mLoadStatus();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Toast.makeText(PageFeed.this, resultCode + "", 0).show();
		switch (requestCode) {
		case STATUS_DETAIL:
			int index = data.getExtras().getInt(PageStatus.STATUS_INDEX, 0);
			Status status = (Status) data.getExtras().getSerializable(
					PageStatus.STATUS_INFO);
			mStatusList.set(index, status);
			mStatusAdapter.notifyDataSetChanged();
			break;
		}

	}

	protected void mLoadStatus() {
		mDialog = ProgressDialog.show(this, "", "Loading");
		ServiceProvider provider = new ServiceProvider(this);
		provider.LoadFeed(mSession.getId(), new AsyncRunnerHeadler() {
			@Override
			public void onComplete(String json) {
				Type type = new TypeToken<ArrayList<Status>>() {
				}.getType();
				final ArrayList<Status> status = new Gson()
						.fromJson(json, type);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mDialog.cancel();
						mStatusList.addAll(status);
						mStatusAdapter.notifyDataSetChanged();
					}
				});
			}

			@Override
			public void onAuthenticate(String json) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mDialog.cancel();
					}
				});
			}

			@Override
			public void onError(int statusCode, String json) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mDialog.cancel();
					}
				});
			}

			@Override
			public void onConnectingError(String message) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mDialog.cancel();
					}
				});
			}
		});
	}

	protected class StatusAdapter extends BaseAdapter {
		private Activity mActivity;

		public StatusAdapter(Activity mActivity) {
			mInflater = LayoutInflater.from(mActivity);
			this.mActivity = mActivity;
		}

		@Override
		public int getCount() {
			return mStatusList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int index, View arg1, ViewGroup arg2) {
			Status mStatus = mStatusList.get(index);
			View mView = null;
			switch (mStatus.getStatusType()) {
			case 0:
			case 1:
				mView = mInflater
						.inflate(R.layout.inc_item_status_normal, null);
				findResource(mView, mStatus, index);
				break;
			case 2:
				mView = mInflater.inflate(R.layout.inc_item_status_checkin,
						null);
				findResource(mView, mStatus, index);
				break;
			}
			return mView;
		}

		private void findResource(View mView, final Status mStatus,
				final int index) {
			ProgressBar pgbLoad = (ProgressBar) mView
					.findViewById(R.id.pgb_item_status_load);
			TextView vlblMessage = (TextView) mView
					.findViewById(R.id.lbl_item_status_message);
			TextView vlblCreate = (TextView) mView
					.findViewById(R.id.lbl_item_status_createtime);
			TextView vlblName = (TextView) mView
					.findViewById(R.id.lbl_item_status_profilename);
			TextView vlblMore = (TextView) mView
					.findViewById(R.id.lbl_item_status_more);
			Button vBtnAdd = (Button) mView
					.findViewById(R.id.btn_item_status_add);

			if (mStatus.getStatusType() == 1) {
				ImageView vImgImage = (ImageView) mView
						.findViewById(R.id.img_item_status_image_priview);
				vImgImage.setVisibility(View.VISIBLE);
			}
			if (mStatus.getCurrentLocation() != null) {
				TextView vlblCurrent = (TextView) mView
						.findViewById(R.id.lbl_item_status_current);
				vlblCurrent.setVisibility(View.VISIBLE);
				vlblCurrent.setText(mStatus.getCurrentLocation().getName());
			}

			if (mStatus.getChildCount() != 0 || mStatus.getLikeCount() != 0) {
				vlblMore.setVisibility(View.VISIBLE);
				vlblMore.setText("");
				if (mStatus.getChildCount() == 1) {
					vlblMore.setText(mStatus.getChildCount() + " Comment");
				}
				if (mStatus.getChildCount() > 1) {
					vlblMore.setText(mStatus.getChildCount() + " Comments");
				}

				if (mStatus.getLikeCount() == 1) {
					vlblMore.setText(vlblMore.getText() + " "
							+ mStatus.getLikeCount() + " Like");
				}
				if (mStatus.getLikeCount() > 1) {
					vlblMore.setText(vlblMore.getText() + " "
							+ mStatus.getLikeCount() + " Likes");
				}
			} else {
				vlblMore.setVisibility(View.GONE);
			}

			vlblMessage.setText(mStatus.getMessage());
			vlblCreate.setText(mStatus.getCreateTime());
			vlblName.setText(mStatus.getFrom().getName());

			vBtnAdd.setVisibility(View.VISIBLE);
			vBtnAdd.setOnClickListener(new AddClick(mStatus, pgbLoad, index));
			mView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(PageFeed.this, PageStatus.class);
					intent.putExtra(PageStatus.STATUS_INDEX, index);
					intent.putExtra(PageStatus.STATUS_INFO, mStatus);
					startActivityForResult(intent, STATUS_DETAIL);
				}
			});
		}

		public class AddClick implements OnClickListener,
				OnActionItemClickListener {
			private QuickAction quickAction;
			private ProgressBar pgbLoad;
			private Status mStatus;
			private int mIndex;

			public AddClick(Status mStatus, ProgressBar pgbLoad, int mIndex) {
				this.pgbLoad = pgbLoad;
				this.mStatus = mStatus;
				this.mIndex = mIndex;
			}

			@Override
			public void onClick(View v) {
				if (mStatus.isCanLike()) {
					if (mStatus.isCanDelete()) {
						mQuickActionCanDelateAndCanLike();
						quickAction.show(v);
					} else {
						mQuickActionNotDelateAndCanLike();
						quickAction.show(v);
					}
				} else {
					if (mStatus.isCanDelete()) {
						mQuickActionCanDelateAndNotLike();
						quickAction.show(v);
					} else {
						mQuickActionNotDelateAndNotLike();
						quickAction.show(v);
					}
				}
			}

			private void mQuickActionCanDelateAndCanLike() {
				ActionItem like = new ActionItem(1, "Like", mActivity
						.getResources().getDrawable(
								R.drawable.ic_menu_mylocation));
				ActionItem comment = new ActionItem(0, "Comment", mActivity
						.getResources().getDrawable(
								R.drawable.ic_menu_mylocation));
				quickAction = new QuickAction(mActivity);
				quickAction.setOnActionItemClickListener(this);

				// add action items into QuickAction
				quickAction.addActionItem(like);
				quickAction.addActionItem(comment);
			}

			private void mQuickActionCanDelateAndNotLike() {
				ActionItem like = new ActionItem(3, "Unlike", mActivity
						.getResources().getDrawable(
								R.drawable.ic_menu_mylocation));
				ActionItem comment = new ActionItem(0, "Comment", mActivity
						.getResources().getDrawable(
								R.drawable.ic_menu_mylocation));
				quickAction = new QuickAction(mActivity);
				quickAction.setOnActionItemClickListener(this);

				// add action items into QuickAction
				quickAction.addActionItem(like);
				quickAction.addActionItem(comment);
			}

			private void mQuickActionNotDelateAndCanLike() {
				ActionItem like = new ActionItem(1, "Like", mActivity
						.getResources().getDrawable(
								R.drawable.ic_menu_mylocation));
				ActionItem comment = new ActionItem(0, "Comment", mActivity
						.getResources().getDrawable(
								R.drawable.ic_menu_mylocation));
				quickAction = new QuickAction(mActivity);
				quickAction.setOnActionItemClickListener(this);

				// add action items into QuickAction
				quickAction.addActionItem(like);
				quickAction.addActionItem(comment);
			}

			private void mQuickActionNotDelateAndNotLike() {
				ActionItem like = new ActionItem(3, "Unlike", mActivity
						.getResources().getDrawable(
								R.drawable.ic_menu_mylocation));
				ActionItem comment = new ActionItem(0, "Comment", mActivity
						.getResources().getDrawable(
								R.drawable.ic_menu_mylocation));
				quickAction = new QuickAction(mActivity);
				quickAction.setOnActionItemClickListener(this);

				// add action items into QuickAction
				quickAction.addActionItem(like);
				quickAction.addActionItem(comment);
			}

			@Override
			public void onItemClick(net.londatiga.android.QuickAction source,
					int pos, int actionId) {
				Intent intent = null;
				switch (actionId) {
				case 0:
					// Comment and more
					intent = new Intent(PageFeed.this, PageStatus.class);
					intent.putExtra(PageStatus.STATUS_INDEX, mIndex);
					intent.putExtra(PageStatus.STATUS_INFO, mStatus);
					startActivityForResult(intent, STATUS_DETAIL);
					break;
				case 1:
					// Like
					mStatusLike();
					break;
				case 2:
					// Delete
					mDelete();
					break;
				case 3:
					// Unlike
					mStatusUnlike();
					break;
				}
			}

			private void mStatusLike() {
				pgbLoad.setVisibility(View.VISIBLE);
				ServiceProvider provider = new ServiceProvider(mActivity);
				provider.StatusLike(mStatus.getId(), new AsyncRunnerHeadler() {
					@Override
					public void onComplete(String json) {
						mStatus.setCanLike(false);
						mStatus.setLikeCount(mStatus.getLikeCount() + 1);
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mStatusList.set(mIndex, mStatus);
								mStatusAdapter.notifyDataSetChanged();
								pgbLoad.setVisibility(View.GONE);
							}
						});
					}

					@Override
					public void onAuthenticate(String json) {
						pgbLoad.setVisibility(View.GONE);
					}

					@Override
					public void onError(int statusCode, String json) {
						pgbLoad.setVisibility(View.GONE);
					}

					@Override
					public void onConnectingError(String message) {
						pgbLoad.setVisibility(View.GONE);
					}
				});
			}

			private void mStatusUnlike() {
				pgbLoad.setVisibility(View.VISIBLE);
				ServiceProvider provider = new ServiceProvider(mActivity);
				provider.StatusUnlike(mStatus.getId(),
						new AsyncRunnerHeadler() {
							@Override
							public void onComplete(String json) {
								mStatus.setCanLike(true);
								mStatus.setLikeCount(mStatus.getLikeCount() - 1);
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										mStatusList.set(mIndex, mStatus);
										mStatusAdapter.notifyDataSetChanged();
										pgbLoad.setVisibility(View.GONE);
									}
								});
							}

							@Override
							public void onAuthenticate(String json) {
								pgbLoad.setVisibility(View.GONE);
							}

							@Override
							public void onError(int statusCode, String json) {
								pgbLoad.setVisibility(View.GONE);
							}

							@Override
							public void onConnectingError(String message) {
								pgbLoad.setVisibility(View.GONE);
							}
						});
			}

			private void mDelete() {
				Toast.makeText(mActivity, "Delete", Toast.LENGTH_LONG).show();
			}
		}

		private LayoutInflater mInflater;
	}

	private ProgressDialog mDialog;
	private StatusAdapter mStatusAdapter;
	private Session mSession;
	private ArrayList<Status> mStatusList;
	private ListView vLvList;
}
